import { StyleSheet, 
  ImageBackground, 
  Text, 
  FlatList,
  ToastAndroid,
  BackHandler,
  View, 
  Image,
  Button,
  Modal,
  TextInput,
  ScrollView,
  TouchableOpacity
} from 'react-native';
import React, { useState,useEffect } from 'react';

let page = 1;
export default function App() {
  const [topics,setTopics] = useState([]);
  const [refresh,setRefresh] = useState(false);
  const getTopics = (page,cb)=>{
    fetch('https://cnodejs.org/api/v1/topics?page='+page)
      .then(res=>res.json())
      .then(res=>{
        cb&&cb(res.data);
      })
  }
  useEffect(()=>{
    getTopics(1,(data)=>setTopics(data));
  },[])
  return (
    <View style={[styles.container]}>
      <FlatList 
        onEndReachedThreshold={0}
        data={topics}
        renderItem={({item}) => <Text 
          numberOfLines={1}
          style={styles.text}>{item.title}</Text>
        }
        keyExtractor={item=>item.id}
        onRefresh={()=>{
          setRefresh(true);
          getTopics(1,(data)=>{
            setTopics(data);
            setRefresh(false);
          });
          
        }}
        refreshing={refresh}
        onEndReached={()=>{
          page++;
          getTopics(page,(data)=>setTopics([...topics,...data]));
          console.log(page);
        }}
      />      
    </View>
  );
}
const styles = StyleSheet.create({
  font:{
    fontSize: 50,
    color: '#f00'
  },
  text:{
    fontSize: 30,
    marginTop: 30,
    width: '70%'
  }
});
